<!DOCTYPE html>
<html lang="zh-Hans">
<meta name="theme-color" content="#FFFFFF">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
  <link rel="icon" sizes="any" mask href="/images/favicon.ico" /> 
  
  

  <!-- viewjs support -->
  
    <!-- for theme: default is false -->
    <!-- for page: default is true -->
    <link  href="./css/viewer.min.css" rel="stylesheet" >
    <script src="./js/viewer.min.js" type="text/javascript" charset="utf-8"></script>
  
  
  
    <meta name="keywords" content="Java,JVM,tech," />
  

  
    <meta name="description" content="分享 Java 技术，做有趣的程序员" />
  
  
  <link rel="icon" type="image/x-icon" href="/logo.png">
  <title>理解VisualVM中的保留大小(Retained Size) [ H E R O ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <div class="nav-container">
    <nav id="menu" class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <!-- <img class="avatar" src="/images/logo.png"> -->
    <span class="title">H E R O</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives/" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags/" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about/" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        理解VisualVM中的保留大小(Retained Size)
      </h1>
      <span>
        
        <time class="time" datetime="2018-08-08T08:30:53.000Z">
          2018-08-08
        </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
        <span class="post-tags">
          <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JVM/" rel="tag">JVM</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/tech/" rel="tag">tech</a></li></ul>
        </span>
      </span>
      
     
    </header>

    <div class="post-content">
      <p>是否在各种内存分析工具中看到过保留大小的概念呐，保留大小到底代表着什么？<br>保留大小代表着实例本事和引用的对象的总大小吗？</p>
<span id="more"></span>
<h2 id="Shallow-Size-and-Retained-Size"><a href="#Shallow-Size-and-Retained-Size" class="headerlink" title="Shallow Size and Retained Size"></a>Shallow Size and Retained Size</h2><p>Shallow Size and Retained Size 的含义都是指的实例对象，不是类本身。</p>
<p>下面将用 sampleClass 表示类Sample的一个实例（instance）</p>
<h3 id="Shallow-Size-含义"><a href="#Shallow-Size-含义" class="headerlink" title="Shallow Size 含义"></a>Shallow Size 含义</h3><p>Shallow Size 就是对象本身所占用的大小，不包括其引用的对象。</p>
<p>举个例子：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SampleClass</span> </span>&#123;</span><br><span class="line">    <span class="comment">// age 属于 Shallow Size</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age = <span class="number">1</span>;</span><br><span class="line">    <span class="comment">// String 类型引用本身 name 属于 Shallow Size，</span></span><br><span class="line">    <span class="comment">// 被引用对象 &quot;SOME_STRING&quot; 不属于 Sample 的实例Shallow Size</span></span><br><span class="line">    <span class="keyword">private</span> String name = SOME_STRING;</span><br><span class="line">    <span class="comment">// 数组所有内容都属于 Shallow Size</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] ids = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Retained-Size-含义"><a href="#Retained-Size-含义" class="headerlink" title="Retained Size 含义"></a>Retained Size 含义</h3><h4 id="针对可达对象"><a href="#针对可达对象" class="headerlink" title="针对可达对象"></a>针对可达对象</h4><p>可达对象就是说，从 GC roots 开始搜索，能够到达的对象，也就是说下一次GC不会被清理的对象，采用下面的计算方法来得到 Retained Size 对象</p>
<p>Retained Size的含义相对于Shallow Size 不太好理解。依然是上面的例子，在不同的情况下，sampleClass 的Retained Size 并不相同。下面引用StackOverFlow上的一个<a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/23941688/yourkit-the-retained-size-of-an-object-doesnt-equal-the-retained-size-of-all">回答</a>来解释这个问题。</p>
<blockquote>
<p><strong>Retained size</strong> of an object is its shallow size plus the shallow sizes of the objects that are accessible, directly or indirectly, only from this object. In other words, the retained size represents the amount of memory that will be freed by the garbage collector when this object is collected.</p>
</blockquote>
<p><img src="https://image-hosting-1251780645.cos.ap-beijing.myqcloud.com/fromSina/0069RVTdgy1fu2cp92ho4j30p00fd0v3.jpg" alt="图一"></p>
<p>上图应该比较容易理解，看起来每个对象的Retained Size 都符合公式（ Retained Size = Shallow Size + 直接子对象的 Retained Size），并没有什么问题，然后我们看另外一种引用关系中，Obj1 的Retained Size 就会发生变化。</p>
<p><img src="https://image-hosting-1251780645.cos.ap-beijing.myqcloud.com/fromSina/0069RVTdgy1fu2cpvt71gj30p00jc76z.jpg" alt="图二"></p>
<p>第二种图中，你会发现Obj2的Retained Size 不再符合我们刚刚总结出来的公式，这是因为Obj2的直接子对象Obj5还被Obj6所引用，造成的结果就是，如果Obj2被回收，Obj5并不会被回收，所以 Obj2 的Retained Size就不应该包括 Obj5 的Retained Size. 虽然 Obj2 的 Retained Size 发生了变化，但是 Obj1 的 Retained Size 并没有发生变化。</p>
<h4 id="针对不可达对象"><a href="#针对不可达对象" class="headerlink" title="针对不可达对象"></a>针对不可达对象</h4><p>指的是下一次 GC 会被清理的对象，也就是说没有其他对象引用自己的对象。</p>
<p>如果你尝试使用 VisualVM 分析dump文件的时候，你会发现有些对象的 Retained Size 居然是0，这个0就推翻了上面那种分析方法的的结论，觉得无论什么样的对象肯定是会有 Shallow Size 的，不可能为0。</p>
<p>通过分析最后可以这样理解：针对不可达对象，也就是可以完全被清除的对象，Retained Size 都是0</p>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><h3 id="理解误区"><a href="#理解误区" class="headerlink" title="理解误区"></a>理解误区</h3><p>好多人是简单的将保留大小描述为，<code>该对象本身和其直接引用或者间接引用的对象的大小的总和</code>。这种理解是片面的，就像上面例子中的 Obj2 一样，如果按照这种理解就会得到错误的结论。</p>
<h3 id="如何在-VisualVM-中计算保留大小（Retained-Size）"><a href="#如何在-VisualVM-中计算保留大小（Retained-Size）" class="headerlink" title="如何在 VisualVM 中计算保留大小（Retained Size）"></a>如何在 VisualVM 中计算保留大小（Retained Size）</h3><p><img src="https://image-hosting-1251780645.cos.ap-beijing.myqcloud.com/fromSina/0069RVTdgy1fu2d8odqlmj31kw0a1ac9.jpg" alt=""></p>
<h3 id="一些-Retained-Size-为-0-的例子"><a href="#一些-Retained-Size-为-0-的例子" class="headerlink" title="一些 Retained Size 为 0 的例子"></a>一些 Retained Size 为 0 的例子</h3><p><img src="https://image-hosting-1251780645.cos.ap-beijing.myqcloud.com/fromSina/0069RVTdgy1fu2d9wrsm0j30ny074dgj.jpg" alt=""></p>

    </div>
    <br>
    <div>全文完。</div>
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Shallow-Size-and-Retained-Size"><span class="toc-text">Shallow Size and Retained Size</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Shallow-Size-%E5%90%AB%E4%B9%89"><span class="toc-text">Shallow Size 含义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Retained-Size-%E5%90%AB%E4%B9%89"><span class="toc-text">Retained Size 含义</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%92%88%E5%AF%B9%E5%8F%AF%E8%BE%BE%E5%AF%B9%E8%B1%A1"><span class="toc-text">针对可达对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%92%88%E5%AF%B9%E4%B8%8D%E5%8F%AF%E8%BE%BE%E5%AF%B9%E8%B1%A1"><span class="toc-text">针对不可达对象</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%99%84%E5%BD%95"><span class="toc-text">附录</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%90%86%E8%A7%A3%E8%AF%AF%E5%8C%BA"><span class="toc-text">理解误区</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%9C%A8-VisualVM-%E4%B8%AD%E8%AE%A1%E7%AE%97%E4%BF%9D%E7%95%99%E5%A4%A7%E5%B0%8F%EF%BC%88Retained-Size%EF%BC%89"><span class="toc-text">如何在 VisualVM 中计算保留大小（Retained Size）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E4%BA%9B-Retained-Size-%E4%B8%BA-0-%E7%9A%84%E4%BE%8B%E5%AD%90"><span class="toc-text">一些 Retained Size 为 0 的例子</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share" style="width: 100%;">
  <img src="/images/wechat-qcode.jpg" height="200" width="200" alt="" style="margin: auto; display: block;" />

  <div style="margin: auto; text-align: center; font-size: 0.8em; color: grey;">关注“豆菽技术”公众号</div>
  
</div>

  
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/curses-programming-with-python.html" rel="next" title="【译】Python Curses 编程">
          【译】Python Curses 编程
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/lock-of-mysql.html" rel="prev" title="MySQL 中的锁">
            MySQL 中的锁
          </a>
          <span>〉</span>
        
      </div>
    </div>
  

  <section class="disqus-comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the <a target="_blank" rel="noopener" href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>
  </section>

  <script>
    var disqus_shortname = 'coderbean';
    
    var disqus_url = 'https://jacobchang.cn/meaning-of-retained-size.html';
    
    (function(){
      var dsq = document.createElement('script');
      dsq.type = 'text/javascript';
      dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
  </script>

  <script id="dsq-count-scr" src="//coderbean.disqus.com/count.js" async></script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item-hide" href="https://jacobchang.cn/" target="_blank">主站</a>
        <!-- <a class="bottom-item-hide">·</a> -->
        <!-- <a class="bottom-item-hide" href="" target="_blank">备份站点</a> -->
        <a class="bottom-item-hide">·</a>
        <a class="bottom-item-hide" href="https://github.com/coderbean" target="_blank">GitHub</a>
        <a class="bottom-item-hide">·</a>
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a>
        <a class="bottom-item">·</a>
        <a class="bottom-item" href="https://github.com/coderbean/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
    <div id="bottom-inner">
        <a class="bottom-item-hide" target="_blank" rel="noopener" href="https://beian.miit.gov.cn">备案号：浙ICP备2021033778号-1</a> 
        <a class="bottom-item-hide">·</a>
        <a id="copyright" class="bottom-item"></a>
    </div>
</footer>

<script language="javascript" type="text/javascript">
    var df = new Date();
    var year = df.getFullYear();
    document.getElementById("copyright").innerHTML = "Copyright © 2017 – " + year + " 黄小豆";
</script>
  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("menu");
      if (logo) {
        logo.onclick = function(event) {
          // returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  


  <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
              m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-155080039-1', 'auto');
      ga('send', 'pageview');
  </script>


  
<link rel='stylesheet' href='https://s3-us-west-2.amazonaws.com/s.cdpn.io/1462889/unicons.css'>

<div class="progress-wrap">
    <svg class="progress-circle svg-content" width="100%" height="100%" viewBox="-1 -1 102 102">
        <path d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98" />
    </svg>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script>

    (function ($) {
        "use strict";
        $(document).ready(function () {
            "use strict";

            //Scroll back to top

            var progressPath = document.querySelector('.progress-wrap path');
            var pathLength = progressPath.getTotalLength();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
            progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
            progressPath.style.strokeDashoffset = pathLength;
            progressPath.getBoundingClientRect();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';
            var updateProgress = function () {
                var scroll = $(window).scrollTop();
                var height = $(document).height() - $(window).height();
                var progress = pathLength - (scroll * pathLength / height);
                progressPath.style.strokeDashoffset = progress;
            }
            updateProgress();
            $(window).scroll(updateProgress);
            var offset = 50;
            var duration = 550;
            jQuery(window).on('scroll', function () {
                if (jQuery(this).scrollTop() > offset) {
                    jQuery('.progress-wrap').addClass('active-progress');
                } else {
                    jQuery('.progress-wrap').removeClass('active-progress');
                }
            });
            jQuery('.progress-wrap').on('click', function (event) {
                event.preventDefault();
                jQuery('html, body').animate({ scrollTop: 0 }, duration);
                return false;
            })


        });

    })(jQuery);
</script>

  
<!-- for theme: default is false -->
<!-- for page: default is true -->
<!-- 图片查看器实例配置 -->
<script type="text/javascript">
    //默认设置， 可以根据个人需求和喜好进行配置
    //详细参考官方说明
    Viewer.setDefaults({
        //设置初始缩放 default: 1
        zoomRatio: [0.5],
        // 过渡动画
        transition:true,
        // 显示工具条
        toolbar: false,
    });
    //获得content中所有的图片， 不同主题可能有所不同
    //为了和其他的图片区别开来 所以在markdown中插入图片的时候使用独特的记号
    //为了一次性得到所有的图片我这里采用的是class = 'article-image'
    var article = document.querySelector('.post-content');
    if(article!=null) {
        var imageList = article.getElementsByTagName('img');
        //将获取到的HTMLCollections转化成Array
        var imageArray = new Array();
        Array.prototype.forEach.call(imageList, element => {
            imageArray.push(element);
        });
        //设置每个图片成为图片组
        Array.prototype.forEach.call(imageList, element => {
            var viewer1 = new Viewer(element);
            viewer1.images = imageArray;
            viewer1.length = imageArray.length;
        });
    }

    
</script>

  
  <! -- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
                processEscapes: true
                    
}
  
        });
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
                  
}
    
        });
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function() {
            var all = MathJax.Hub.getAllJax(), i;
            for(i=0; i < all.length; i += 1) {
                            all[i].SourceElement().parentNode.className += ' has-jax';
                                    
            }
                
        });
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>

</script>

  
</body>

</html>